<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My WebSocket</title>

    <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
<a onclick="join()" href="#">加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入加入</a>
<br/>
<a onclick="tick()" href="#">打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打打</a>
</body>

<script type="text/javascript">


    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }


    var token = getQueryString("token");

    function initWebSocket(token) {
        var websocket;

        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://10.168.1.182/school");
        } else {
            alert('Sorry, websocket not supported by your browser.')
        }
        websocket.token = token;

        websocket.join = function () {
            var message = {messageType: 0, request: {userToken: websocket.token}}
            websocket.send(JSON.stringify(message));
        }

        websocket.tick = function () {
            var message = {
                messageType: 2,
                request: {userId: websocket.selfId, roomNum: websocket.roomNum, userToken: websocket.token}
            }
            websocket.send(JSON.stringify(message));
        }
        //Error callback
        websocket.onerror = function () {
            alert("onerror")
        };

        //socket opened callback
        websocket.onopen = function (event) {
            websocket.join();
        }


        websocket.onmessage = function (event) {
            console.log(event.data)
            var data = JSON.parse(event.data)
            if (data.type == 1) {
                websocket.roomNum = data.roomNum;
                websocket.selfId = data.self.id;
                websocket.selfName = data.self.name;
            }
            if (data.type == 3) {
                if (data.self) {
                    $("#self").text(data.totalScore)
                } else {
                    $("#enemy").text(data.totalScore)
                }
            }

            if (data.type == 6) {
                if (data.win) {
                    alert("赢了")
                } else {
                    alert("输了")
                }
            }
        }

        //socket closed callback
        websocket.onclose = function () {
            alert("close")
        }


        return websocket;
    }


    var web1 = initWebSocket("d04380774375cd34133c27a38af1454f")
    var web2 = initWebSocket("fac860d744306e3d78dcdcd549738fb1")

    function tick() {
        web1.tick();
        web2.tick();
    }


    function join() {
        web1.join();
        web2.join();
    }
</script>
</body>
</html>
